import pyaudio
import numpy as np
import queue
import time
from .base import AudioSource

class MicrophoneSource(AudioSource):
    """麦克风音频源"""
    def __init__(self, chunk_size: int = 1024, channels: int = 1, rate: int = 16000):
        self.chunk_size = chunk_size
        self.channels = channels
        self.rate = rate
        self.audio_queue = queue.Queue()
        self.is_running = False
        self.stream = None
        self.p = None

    def audio_callback(self, in_data, frame_count, time_info, status):
        if status:
            print(f"状态: {status}")
        audio_data = np.frombuffer(in_data, dtype=np.float32)
        self.audio_queue.put(audio_data)
        return (in_data, pyaudio.paContinue)

    def start(self):
        self.is_running = True
        self.p = pyaudio.PyAudio()
        print("可用的输入设备:")
        for i in range(self.p.get_device_count()):
            dev_info = self.p.get_device_info_by_index(i)
            if dev_info['maxInputChannels'] > 0:
                print(f"{i}: {dev_info['name']}")
        default_input = self.p.get_default_input_device_info()
        print(f"\n使用默认输入设备: {default_input['name']}")
        self.stream = self.p.open(
            format=pyaudio.paFloat32,
            channels=self.channels,
            rate=self.rate,
            input=True,
            frames_per_buffer=self.chunk_size,
            stream_callback=self.audio_callback
        )
        print("\n开始录音，按 Ctrl+C 停止...")
        print("=" * 50)
        try:
            self.stream.start_stream()
            while self.stream.is_active():
                time.sleep(0.1)
        except KeyboardInterrupt:
            print("\n停止录音...")
        finally:
            self.stop()

    def stop(self):
        self.is_running = False
        if self.stream:
            self.stream.stop_stream()
            self.stream.close()
        if self.p:
            self.p.terminate() 